<?php

trait Trait_Api_Tongyong
{

    /**
     * 获得套餐
     * @param  array  $params
     * User: netman
     * Date: 2023/10/17 9:57
     */
    public function get_current_suit(array $params)
    {
        $suit_id = $params['suit_id'];//套餐id
        $use_date = $params['use_date'];//使用时间
        $product_id = $params['product_id'];//产品id
        $list = Model_Tongyong::current_suit_price($product_id, $suit_id, $use_date);
        if (empty($list)) {
            throw new Exception('未找到信息');
        } else {
            //获得套餐信息
            $suitdetail = DB::select()->from('model_suit')
                ->where('productid', '=', $product_id)
                ->and_where('id', '=', $suit_id)
                ->execute()->current();
            $suitdetail['paytype_name'] = $suitdetail['paytype']!=2 ? '全款支付' : '定金支付';
            $list['suitdetail'] = $suitdetail;
            $list['description'] = $this->content_add_domain($list['description']);
            return $list;
        }
    }

    /**
     * 获取属性
     * @param  array  $params
     * User: netman
     * Date: 2023/10/17 9:57
     */
    public function get_attr(array $params)
    {
        $typeid = $params['type_id'];//扩展产品id
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            )
        );
        //属性
        $result['attribute'] = DB::select('id', 'attrname')->from('model_attr')
            ->where('pid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->and_where('typeid', '=', $typeid)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()->as_array();
        foreach ($result['attribute'] as &$item) {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('model_attr')
                ->where('pid', '=', $item['id'])
                ->and_where('isopen', '=', 1)
                ->and_where('typeid', '=', $typeid)
                ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
                ->execute()->as_array();
        }
        return $result;
    }

    /**
     * 套餐日历报价
     * @param  array  $params
     * User: netman
     * Date: 2023/10/17 10:25
     */
    public function suit_calendar_price(array $params)
    {
        $product_id = $params['product_id'];
        $suit_id = $params['suit_id'];;
        $date = strtotime(date('Y-m-d', time()));
        $day = DB::select('productid', 'suitid', 'day', 'price',
            'number')->from('model_suit_price')->where("productid={$product_id} and suitid={$suit_id} and day>={$date}")->execute()->as_array();
        foreach ($day as &$v) {
            $v['date'] = date('m-d', $v['day']);
            $v['time'] = date('Y-m-d', $v['day']);
            $v['price'] = Currency_Tool::price($v['price']);
        }
        return array(
            'data' => $day,
            'status' => true
        );
    }

    /**
     * @desc 属性生成where条件,用于多条件属性搜索
     * @param $attrid
     * @return string
     */
    private function get_attr_where($attrid)
    {
        $arr = Common::remove_arr_empty(explode('_', $attrid));
        foreach ($arr as $value) {
            $value = (int)$value;
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,sline_a.attrid) ";
            }
        }

        return $str;
    }


    //通用介绍

    /**
     * 获取套餐
     * @param $id
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/10/17 11:43
     */
    private function get_min_suit($id, $params = [])
    {
        $sql = "productid={$id} ";
        if($params['card_suit_id']){
            $sql.= " and id={$params['card_suit_id']} ";
        }
        $suitModel = ORM::factory('model_suit')->where($sql)->order_by('displayorder', 'asc')->get_all();
        $date = strtotime(date('Y-m-d', time()));
        foreach ($suitModel as &$v) {
            $model_suit_price = DB::select()
                ->from("model_suit_price")
                ->and_where_open()
                ->where('number', '>',0)
                ->or_where('number', '=',-1)
                ->and_where_close()
                ->and_where('suitid', '=', $v['id'])
                ->and_where('productid', '=', $v['productid'])
                ->and_where("day", '>=', $date)
                ->order_by('price', 'asc')
                ->execute()
                ->current();
            $v['number'] = $model_suit_price ? 1 : 0;
            $v['paytype_name'] = $v['paytype']!=2 ? '全款支付' : '定金支付';
            $v['description'] = Model_Api_V2_System::filter_content($v['description']);
            $price = $model_suit_price['price'];
            if ($price > 0) {
                $v['price'] = Currency_Tool::price($price);
            } else {
                $v['price'] = 0;
            }
        }
        return $suitModel;
    }

    /**
     * 格式化数据
     * @param $arr
     * @return array
     * User: netman
     * Date: 2023/10/12 13:45
     */
    private function format_tongyong($arr)
    {
        $data = array();
        foreach ($arr as $v) {
            $out = [];
            // 最终目的地
            $out['finaldest_name'] = Model_Api_V2_System::get_finaldest_name($v['finaldestid']);
            $out['commentnum'] = Model_Comment::get_comment_num($v['id'], $v['typeid']); //评论次数
            $out['sellnum'] =  Model_Member_Order::get_sell_num($v['id'],$v['typeid']) + intval($v['bookcount']); //销售数量;
            $out['score'] = St_Functions::get_satisfy($v['typeid'], $v['id'], $v['satisfyscore'],
                array('suffix' => ''));
            $out['attrlist'] = Model_Model_Attr::get_attr_list($v['attrid'], $v['typeid']);//属性列表.
            $out['iconlist'] = $this->icons($v['iconlist']);
            $out['litpic'] = $this->img_url($v['litpic'], 220, 150);
            $out['price'] = $this->get_min_price($v['id']);
            $out['id'] = $v['id'];
            $out['title'] = $v['title'];
            $out['sellpoint'] = $v['sellpoint'];
            $data[] = $out;
            unset($out);
        }
        return $data;
    }

    /**
     * 获取最低价格
     * @param $id
     * @return float|int|mixed|number
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/10/17 9:42
     */
    private function get_min_price($id)
    {
        Model_Tongyong::updateMinPrice($id);
        $data = DB::select('price')->from('model_archive')->where('id', '=', $id)->execute()->current()['price'];
        $data = Currency_Tool::price($data);
        return $data;
    }

    private function get_content($params)
    {
        $default = array(
            'typeid' => $params['typeid'],
            'productinfo' => $params['productinfo'],
            'onlyrealfield' => 1,
            'pc' => 0

        );

        $params = array_merge($default, $params);
        extract($params);

        $isExists = DB::select()->from('model')->where("id={$params['typeid']}")->execute()->current();
        if (empty($isExists)) {
            return '';
        }
        $table = 'sline_model_content';
        $extend_tables = "sline_{$isExists['addtable']}";


        $sql = "SELECT columnname,chinesename,isrealfield FROM {$table} ";

        $sql .= "WHERE webid=0 and isopen=1 and typeid=".$params['typeid'];

        $sql .= " ORDER BY displayorder ASC";
        $arr = DB::query(1, $sql)->execute()->as_array();

        //扩展表数据
        $productid = $params['productinfo']['id'];//产品id
        $sql = "SELECT * FROM $extend_tables WHERE productid='$productid'";
        $ar = DB::query(1, $sql)->execute()->as_array();
        $list = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian') {
                continue;
            }
            $content = ! empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
            $content = $content ? $content : '';

            if (empty($content)) {
                continue;
            }

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] = Model_Api_V2_System::filter_content($content);
            $list[] = $a;
        }
        return $list;
    }


}